package com.yifei.exception;


import com.yifei.model.enums.ResultCode;
import com.yifei.model.result.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 全局异常处理
 * @author: yiFei
 * @date: 2022/1/4 3:14
 */
@RestControllerAdvice
public class GlobalException {

    private static final Logger log = LoggerFactory.getLogger(GlobalException.class);

    /**
     * 全局异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<String> Exception(Exception e) {
        e.printStackTrace();
        log.error("未捕获错误 {} 错误class {}", e.getMessage(), e.getClass());
        return Result.customize(ResultCode.SYSTEM_EXCEPTION_ERROR);
    }

    @ExceptionHandler(ServiceException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<String> Exception(ServiceException e) {
        return Result.customize(e.getResultCode());
    }

    /**
     * 用户传入参数错误
     *
     * @param e
     * @return
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<String> IllegalArgumentException(IllegalArgumentException e) {
        log.error("IllegalArgumentException 错误 {}", e.getMessage());
        return Result.customize(ResultCode.REQUEST_PARAMETER_ERROR);
    }

    // 处理的异常类型  TODO 未测试此项异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result<Map<String, String>> handleValidException(MethodArgumentNotValidException e) {
        log.error("数据校验出现问题{},异常类型：{}", e.getMessage(), e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach(fieldError -> errorMap.put(fieldError.getField(), fieldError.getDefaultMessage()));
        //参数校验异常
        return Result.customize(ResultCode.REQUEST_PARAMETER_ERROR, errorMap);
    }

}
